<?php
/**
 * Created by PhpStorm.
 * User: Reborn
 * Date: 2019/12/5
 * Time: 10:38
 */

namespace app\common\exception;

use think\exception\HttpResponseException;
use think\facade\Log;
use think\Response;
use Throwable;

class Http extends \Exception
{
    protected $requestID;

    public function __construct($message = "", $code = 500, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);

        // 参数验证错误
        $this->requestID = strtoupper(uniqid(date('ymdHis') . create_random_string(2), true));
        $this->ajaxError($message,$code);
    }

    /**
     * 返回失败
     * User Reborn
     * Time 2020/3/30 16:25
     * @param $code
     * @param string $message
     * @param array $header
     * @return Response
     */
    protected function ajaxError($message='', $code='', array $header = []): Response
    {
        $result = [
            'status' => 0,
            'now' => time(),
            'code' => (string)$code,
            'info'  => (string)$message,
            'data' => '',
            'req_id' => $this->requestID,
        ];
        $this->writeRequestLog($result);
        $response=Response::create($result, 'json')->header($header);
        throw new HttpResponseException($response);
    }

    /**
     * 记录响应的日志
     * @param $result
     */
    protected function writeRequestLog($result)
    {
        $log = date('Y-m-d H:i:s') . "  \r\n";
        $log .= 'return:' . \json_encode($result, JSON_UNESCAPED_UNICODE) . "\r\n\r\n";
        Log::write($log);
    }
}